package com.nio.pipe;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class PipeDemo {
    public static void main(String[] args) throws IOException {
        // 1.获取通道
        Pipe pipe = Pipe.open();
        // 2.获取sink通道
        Pipe.SinkChannel sink = pipe.sink();
        // 3.创建缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        byteBuffer.put("java".getBytes()); // 创建数据
        byteBuffer.flip();
        // 4,写入数据
        sink.write(byteBuffer);
        // 5.获取source通道,读取数据
        Pipe.SourceChannel source = pipe.source();
//        // 6.创建缓冲区读取数据
//        ByteBuffer byteBuffer2 = ByteBuffer.allocate(1024);
        byteBuffer.flip();
        int length = source.read(byteBuffer);
        System.out.println(new String(byteBuffer.array(),0,length));
        // 关闭通道
        source.close();
        sink.close();
    }
}
